<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div {
            position: absolute;
            width: 200px;
            height: 200px;
            background-color: pink;
        }
    </style>
</head>
<body>
    <button class="btn500">500</button>
    <button class="btn800">800</button>
    <div></div>
    <script>
        //获得元素
        var btn500 = document.querySelector('.btn500')
        var btn800 = document.querySelector('.btn800')
        var div = document.querySelector('div')
        //动画函数
        function animate(obj, target, callback) {
            //防止多次点击，先清除一次定时器
            clearInterval(obj.timer)
            //设置定时器，把定时器添加为参数的属性，方便区分
            obj.timer = setInterval(function() {
                //步长
                var tep = (target - obj.offsetLeft) / 10
                tep = tep > 0 ? Math.ceil(tep) : Math.floor(tep)
                //到达目标值停止动画
                if(obj.offsetLeft == target) {
                    clearInterval(obj.timer)
                    //有回调函数则执行回函数
                    callback && callback()
                } else {
                    obj.style.left = obj.offsetLeft + tep + 'px'
                }
            }, 15)
        }
        //点击事件
        btn500.addEventListener('click', function() {
            animate(div, 500)
        })
        btn800.addEventListener('click', function() {
            animate(div, 800)
        })
    </script>
</body>
</html>